<template>
  <div id="user-info-page">
    <h1 class="page-title">我的信息</h1>
    <el-card v-if="user" class="user-card">
      <el-form label-position="left" label-width="100px" class="user-info">
        <el-form-item label="用户名">
          <el-input v-model="user.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="手机号码">
          <el-input v-model="user.tel_number"></el-input>
        </el-form-item>
        <el-form-item label="QQ">
          <el-input v-model="user.qq_number"></el-input>
        </el-form-item>
        <el-form-item label="学院">
          <el-select v-model="user.college_id" placeholder="请选择" @change="fetchClassesData">
            <el-option v-for="college in colleges" :key="college.id" :label="college.name"
              :value="college.id"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="年级">
          <el-select v-model="user.grade" placeholder="请选择" @change="fetchClassesData">
            <el-option v-for="year in years" :key="year" :label="year" :value="year"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="班级">
          <el-select v-model="user.class_name" placeholder="请选择" @change="handleClassChange">
            <el-option v-for="classItem in classes" :key="classItem.id" :label="classItem.name"
              :value="classItem.name"></el-option>
          </el-select>
          <div class="sensitive-info-hint">敏感信息请联系管理员</div>
        </el-form-item>
        <el-form-item label="是否为班委">
          <el-select v-model="user.com_member_type" placeholder="请选择">
            <el-option label="是" :value="1"></el-option>
            <el-option label="否" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitUserInfo">提交</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-empty v-else description="暂无用户信息"></el-empty>
  </div>
</template>

<script>
import { ref, onMounted } from "vue";
import axios from 'axios';
import { ElCard, ElEmpty, ElForm, ElFormItem, ElInput, ElSelect, ElOption, ElButton } from "element-plus";
import { fetchColleges, fetchClasses } from "@/api/api"; // 确保路径正确

export default {
  name: "UserInfo",
  components: {
    ElCard,
    ElEmpty,
    ElForm,
    ElFormItem,
    ElInput,
    ElSelect,
    ElOption,
    ElButton,
  },
  setup() {
    const user = ref({
      username: '',
      tel_number: '',
      qq_number: '',
      college_id: '',
      college_name: '',
      class_id: '',
      class_name: '',
      grade: '',
      com_member_type: 0,
    });
    const originalUser = ref({}); // 用于存储原始用户数据
    const colleges = ref([]);
    const classes = ref([]);
    const years = ref(Array.from({ length: new Date().getFullYear() - 1900 }, (_, i) => new Date().getFullYear() - i));

    const fetchClassesData = async () => {
      if (user.value.college_id && user.value.grade) {
        try {
          const classesResponse = await fetchClasses(user.value.grade, user.value.college_id);
          classes.value = classesResponse;
          if (classesResponse.length > 0) {
            user.value.class_id = classesResponse[0].id;
            user.value.class_name = classesResponse[0].name;
          }
        } catch (error) {
          console.error('获取班级列表出错:', error);
        }
      }
    };

    onMounted(async () => {
      try {
        const userData = localStorage.getItem("user");
        if (userData) {
          originalUser.value = JSON.parse(userData); // 保存原始用户数据
          user.value = { ...originalUser.value, ...JSON.parse(userData) };
          const userId = user.value.id;
          const studentInfoResponse = await axios.get(`/api/v1/student/info`, { params: { id: userId } });
          if (studentInfoResponse.data.code === 200) {
            user.value = { ...user.value, ...studentInfoResponse.data.data };
          }
        }

        const collegesResponse = await fetchColleges();
        colleges.value = collegesResponse;
        if (user.value.college_id && user.value.grade) {
          const classesResponse = await fetchClasses(user.value.grade, user.value.college_id);
          classes.value = classesResponse;
          //console.log(classesResponse)
        }
      } catch (error) {
        console.error('获取用户信息或学院班级信息出错:', error);
      }
    });

    const handleClassChange = (newClassName) => {
      const selectedClass = classes.value.find(c => c.name === newClassName);
      if (selectedClass) {
        user.value.class_id = selectedClass.id;
        user.value.class_name = selectedClass.name;
      }
    };

    const submitUserInfo = async () => {
      const sensitiveInfoModified = user.value.college_id !== originalUser.value.college_id ||
        user.value.grade !== originalUser.value.grade ||
        user.value.class_id !== originalUser.value.class_id ||
        user.value.com_member_type !== originalUser.value.com_member_type;

      if (sensitiveInfoModified) {
        // 敏感信息被修改，调用 create_altering API
        try {
          const response = await axios.post('/api/v1/student/create_altering', {
            id: user.value.id,
            class_id: user.value.class_id,
            com_member_type: user.value.com_member_type,
          });
          console.log(response.data.data);
          alert('敏感信息修改申请已发送给管理员');
        } catch (error) {
          console.error('发送敏感信息修改申请失败:', error);
        }
      } else {
        // 非敏感信息修改，调用 update API
        try {
          const response = await axios.post('/api/v1/student/update', {
            id: user.value.id,
            tel_number: user.value.tel_number,
            qq_number: user.value.qq_number,
          });
          console.log(response);
          alert('信息更新成功');
        } catch (error) {
          console.error('更新信息失败:', error);
        }
      }
    };

    return {
      user,
      originalUser,
      colleges,
      classes,
      years,
      fetchClassesData,
      submitUserInfo,
      handleClassChange,
    };
  },
};
</script>

<style scoped>
#user-info-page {
  padding: 20px;
  background-color: #ffffff;
  min-height: 100vh;
}

.page-title {
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 20px;
  text-align: center;
  color: #333;
}

.user-card {
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.user-info {
  margin-top: 20px;
}

.info-item {
  margin-bottom: 10px;
  font-size: 16px;
}

.label {
  font-weight: bold;
  color: #333;
}

.value {
  color: #666;
}

.sensitive-info-hint {
  font-size: 12px;
  color: #999;
}
</style>